package com.taomeng.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by tao
 */
@WebFilter("*.jsp")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String currentURL = request.getRequestURI();
        System.out.println("currentURL:" + currentURL);
        String ctxPath = request.getContextPath();
        System.out.println("ctxPath:" + ctxPath);
        //除掉项目名称时访问页面当前路径
        String targetURL = currentURL.substring(ctxPath.length());
        System.out.println("targetURL:" + targetURL);
        //登录页面
        String loginPage = "/login.jsp";
        //登陆成功跳转的url
        String mainPage = "/admin/public/main.jsp";
        //登录的Servlet对应的url
        String loginServlet = "/account";
//        HttpSession session = request.getSession(false);

        Subject currentUser = SecurityUtils.getSubject();

        //没有认证的情况下
        if (!currentUser.isAuthenticated()) {
            //当前页面是登录页和登录servlet，放行
            if (loginPage.equals(targetURL)||targetURL.equals(mainPage)) {
                chain.doFilter(request, response);
                return;
            }else{
                //不是登录页和认证servlet就重定向到登录页
                response.sendRedirect(ctxPath + loginPage);
                System.out.println("redirect:" + ctxPath + loginPage);
                return;
            }
        } else {
            //在已经认证的情况下，如果访问登录页，直接重定向到主页
            if (loginPage.equals(targetURL)) {
                response.sendRedirect(ctxPath + mainPage);
                System.out.println("redirect:" + ctxPath + mainPage);
                return;
            }else{
                chain.doFilter(request, response);
                return;
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
